package com.tongguan.paypos.view.calendar;

import android.annotation.SuppressLint;
import android.app.ActionBar.LayoutParams;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.tongguan.paypos.R;
import com.tongguan.paypos.utils.DateUtils;
import com.tongguan.paypos.utils.ToastUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 弹出时间选择
 * 
 * @author liujian
 * 
 */
public class TimePopWind implements OnClickListener {
	private Context context;
	private View view;
	private RelativeLayout mBeginTimeLayout, mEndTimeLayout;
	private TextView mBeginTimeTx, mEndTimeTx;
	private Button mSearchBt;
	private PopupWindow mPopupWindow;
	//自定义获取时间接口
	private static ITimeCallBack mTimeCallBack;
	public interface ITimeCallBack {
		void queryByTime(String startTime, String endTime);
	}
	public static void setmTimeCallBack(ITimeCallBack mTimeCallBack) {
		TimePopWind.mTimeCallBack = mTimeCallBack;
	}
	
	public TimePopWind(Context context) {
		this.context = context;
		initView();
	}

	// 日历控件
	private AlertDialog theDialog;
	private CalendarPickerView dialogView;
	private Calendar nextYear, lastYear;
	private int screenWidth;
	//当前时间
	private String currTime;
	// 初始化界面
	private void initView() {
		currTime= DateUtils.getDate();
		screenWidth = context.getResources().getDisplayMetrics().widthPixels;
		view = LayoutInflater.from(context).inflate(R.layout.time_pop, null);
		mBeginTimeLayout = (RelativeLayout) view
				.findViewById(R.id.begin_layout);
		mEndTimeLayout = (RelativeLayout) view.findViewById(R.id.end_layout);

		mBeginTimeTx = (TextView) view.findViewById(R.id.begin_time);
		mBeginTimeTx.setText(DateUtils.getBeforeDate(-7));
		mEndTimeTx = (TextView) view.findViewById(R.id.end_time);
		mEndTimeTx.setText(DateUtils.getDate_());
		mSearchBt = (Button) view.findViewById(R.id.search_bt);

		mBeginTimeLayout.setOnClickListener(this);
		mEndTimeLayout.setOnClickListener(this);
		mSearchBt.setOnClickListener(this);

		// 日历相关
		nextYear = Calendar.getInstance();
		nextYear.add(Calendar.YEAR, 2);
		lastYear = Calendar.getInstance();
		lastYear.add(Calendar.YEAR, -2);
		dialogView = (CalendarPickerView) LayoutInflater.from(context).inflate(
				R.layout.time_dialog, null);
		dialogView.init(lastYear.getTime(), nextYear.getTime())
				.withSelectedDate(new Date());
		theDialog = new AlertDialog.Builder(context)
				 /*.setTitle("请选择时间") */.create();
		theDialog.setView(dialogView, 0, 0, 0, 0);
		theDialog.setOnShowListener(new DialogInterface.OnShowListener() {
			@Override
			public void onShow(DialogInterface dialogInterface) {
//				int screenHeight=context.getResources().getDisplayMetrics().heightPixels;
//				dialogView.fixDialogDimens(dip2px(context, 400), (int)(screenHeight * 0.6));
				dialogView.fixDialogDimens(0.8f, 0.6f);
			}
		});
	}
	private void showDialog(TextView textView) {
		theDialog.show();
		dialogView.setmIGMT(new CalendarPickerView.IGMTCallback() {

			@Override
			public void gmtTime(Date date, TextView mTextView) {
//				Fri Nov 14 00:00:00 GMT+08:00 2014
//				                    CST（中国）
//				Sat Nov 01 00:00:00 格林尼治标准时间+0800 2014
				// TODO Auto-generated method stub
				String time=date.toString();
				String str0_19=time.substring(0, 19);
				String end_n_4=time.substring(time.length()-4, time.length());
				String k=" ";
				String t = str0_19+k+"格林尼治标准时间+0800"+k+end_n_4;
				String selectDate=timeChange(t);
				//判断
				if(Long.parseLong(selectDate.replace("-", ""))>Long.parseLong(currTime)){
					ToastUtils.showCustom(context, "开始和结束日期不能大于当天日期");
					return ;
				}
				mTextView.setText(selectDate);
				theDialog.dismiss();
			}
		}, textView);
	}

	private String timeChange(String date) {
		try {
			SimpleDateFormat sdf1 = new SimpleDateFormat(
					"EEE MMM dd HH:mm:ss 格林尼治标准时间+0800 yyyy", Locale.ENGLISH);
			Date d = sdf1.parse(date);
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
			return sdf2.format(d).toString();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 显示
	 * 
	 * @param belowView
	 * @return
	 */
	@SuppressLint("InlinedApi")
	public PopupWindow showPopWindows(View belowView) {
		mPopupWindow = new PopupWindow(view, screenWidth,
				LayoutParams.WRAP_CONTENT);
		// mPopupWindow.setTouchable(true);
		// mPopupWindow.setFocusable(true);
		// mPopupWindow.setBackgroundDrawable(new ColorDrawable(0));
		mPopupWindow.setOutsideTouchable(true);
		mPopupWindow.showAsDropDown(belowView);
		dispathEvent(view);
		return mPopupWindow;
	}

	/**
	 * 取消显示的pop
	 */
	public void dissPopupWindow(PopupWindow mPopupWindow) {
		if (null != mPopupWindow && mPopupWindow.isShowing()) {
			mPopupWindow.dismiss();
		}
	}

	private void dispathEvent(View view) {
		view.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				if (null != mPopupWindow && mPopupWindow.isShowing()) {
					mPopupWindow.dismiss();
				}
				return false;
			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.begin_layout:
			showDialog(mBeginTimeTx);
			break;
		case R.id.end_layout:
			showDialog(mEndTimeTx);
			break;
		case R.id.search_bt:
			if(isOkTime()){
				try {
					mTimeCallBack.queryByTime(mBeginTimeTx.getText().toString().trim(),mEndTimeTx.getText().toString().trim());
				} catch (Exception e) {
					// TODO: handle exception
				}
				dissPopupWindow(mPopupWindow);
			}
			break;
		default:
			break;
		}
	}
	
	//判断两个时间
	private boolean isOkTime(){
		String startTime = mBeginTimeTx.getText().toString().replace("-", "");
		String endTime = mEndTimeTx.getText().toString().replace("-", "");
		if(Long.parseLong(startTime) > Long.parseLong(endTime)){
			 ToastUtils.showCustom(context, "开始日期不能大于结束日期");
			return false;
		}
		return true;
	}

}
